package com.example.demo.Gmail.controller;


import com.example.demo.Gmail.Excutor.ThreadResponse;
import com.example.demo.Gmail.Excutor.pullThead;
import com.example.demo.Gmail.GmailServiceResponse;
import com.example.demo.Gmail.Handle.GmailHandle;
import com.example.demo.Gmail.Handle.PartsHandle;
import com.example.demo.Gmail.Handle.proxyHandler;
import com.example.demo.Gmail.model.*;
import com.example.demo.Gmail.service.BackendService;
import com.example.demo.Gmail.service.GmailService;
import com.example.demo.Gmail.service.UserService;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.*;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.lang.Thread;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@RestController
@RequestMapping("gmail")
@Api(description ="邮箱管理接口")
public class GmailController {
    private final String USERID="me";
    private final String URL="http://download.files.cnexps.com/";
    @Autowired
    GmailService gmailService;
    @Autowired
    BackendService backendService;

    @Autowired
    UserService userService;

    @PostMapping("sendEmail")
    @ApiOperation(value = "发送邮件",notes = "发送邮件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", name = "emailAddress", value = "邮箱地址", required = true, dataType = "String"),
    })
    public GmailServiceResponse<MessageModel> sendEmail(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true)MailSenderInfo mailSenderInfo,@RequestParam String emailAddress) throws Exception {
            //大陆环境需要加代理
            proxyHandler.proxy();
            GmailServiceResponse response=new GmailServiceResponse();
            try {
                UserModel user= userService.getUser(emailAddress);
                Gmail service= GmailHandle.service(user);
                MimeMessage mimeMessage= GmailHandle.createEmailWithAttachment(mailSenderInfo);
                Message message= gmailService.sendMessage(service,USERID,mimeMessage);
                String ID=  message.getId();
                MessageModel messageModel=   PartsHandle.buildMongoData(ID,mailSenderInfo);
                messageModel.setEmailAddress(emailAddress);
                backendService.sentAndInsert(messageModel);
                response.setData(messageModel);
                return response;
            }catch (Exception e){
                response.setMsg(e.getMessage());
                return response;
            }
    }

    @ApiOperation(value = "分页查询",notes = "分页查询")
    @PostMapping("pageQuery")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "label",value = "邮箱类型",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "currentPage",value = "当前页码",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "每页多少条",required = true,dataType = "String")
    })
    public GmailServiceResponse pageQuery(@RequestParam String emailAddress,@RequestParam String label,
                                                          @RequestParam String currentPage,@RequestParam String pageSize) throws InterruptedException, ExecutionException {
        GmailServiceResponse response =new GmailServiceResponse();
        ThreadResponse threadResponse =  new ThreadResponse(emailAddress,Integer.valueOf(currentPage),Integer.valueOf(pageSize),label,backendService);
       // FutureTask<List<ThreadResponse>> result = new FutureTask<>(threadResponse);
        FutureTask<ThreadResponse> result = new FutureTask<>(threadResponse);
        Thread thread=new Thread(result);
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
        // 遍历线程组树，获取根线程组
        while (group != null) {
            topGroup = group;
            group = group.getParent();
        }
        // 激活的线程数再加一倍，防止枚举时有可能刚好有动态线程生成
        int slackSize = topGroup.activeCount() * 2;
        Thread[] slackThreads = new Thread[slackSize];
        // 获取根线程组下的所有线程，返回的actualSize便是最终的线程数
        int actualSize = topGroup.enumerate(slackThreads);
        Thread[] atualThreads = new Thread[actualSize];
        // 复制slackThreads中有效的值到atualThreads
        System.arraycopy(slackThreads, 0, atualThreads, 0, actualSize);
        int count=0;
        for (Thread threadImport : atualThreads) {
            if (threadImport.getName().equals(emailAddress+label)){
                count++;
                threadImport.join();
                thread.start();
            }
        }
        if (count==0){
            thread.start();
        }
        Page<MessageModel>  page= (Page<MessageModel>) result.get();
        //开启监听邮箱动作
        try {
            Thread watchThread= new Thread(new pullThead(userService,backendService));
            watchThread.start();
        }catch (Exception e){
            response.setMsg(e.getMessage());
        }
        if (page.getContent().size()==0){
            response.setData(null);
            response.setSuccess(false);
            response.setMsg("当前用户googgle邮箱无任何数据");
        }else {
            response.setData(page);
            response.setSuccess(true);
            response.setMsg("获取数据成功");
        }
        return response;

    }

    /**
     * 批量删除邮件
     * @param ids
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */

    @ApiOperation(value = "批量删除邮件",notes = "批量删除邮件")
    @DeleteMapping(value = "batchDelete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "ids[]",value = "邮箱messageid数组",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String")
    })
    public GmailServiceResponse batchDelete(@RequestParam String ids[],@RequestParam String emailAddress) throws GeneralSecurityException, IOException {
        //大陆环境需要加代理
        proxyHandler.proxy();
        UserModel user= userService.getUser(emailAddress);
        Gmail service=GmailHandle.service(user);
        GmailServiceResponse response=new GmailServiceResponse();
        try {
            gmailService.batchDelete(service,USERID,ids);
            response.setSuccess(true);
            response.setData(ids);
            response.setMsg("删除数据成功");
            return response;
        }catch (Exception e){
            e.printStackTrace();
            response.setSuccess(false);
            response.setMsg("删除数据失败,删除邮件id未找到");
            return response;
        }
    }


    /**
     * 根据邮箱和id获得指定数据
     * @param emailAddress
     * @param messageId
     * @return
     */
    @ApiOperation(value = "获取指定邮件信息",notes = "获取指定邮件信息")
    @GetMapping("getMessage")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "一个用户的messageId是唯一的，根据此获取邮箱信息",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String")
    })
    public GmailServiceResponse getMessage(@RequestParam String emailAddress,@RequestParam String messageId){
        GmailServiceResponse response =new GmailServiceResponse();
        MessageModel messageModel=  backendService.getMessage(messageId,emailAddress);
        if (messageModel==null){
            response.setMsg("请检查邮箱id是否正确");
            response.setSuccess(false);
            return response;
        }else {
            response.setSuccess(true);
            response.setMsg("获取数据成功");
            response.setData(messageModel);
            return response;
        }

    }
    /**
     * 根据邮箱和id更新邮件为已读状态
     * @param emailAddress
     * @param messageId
     * @return
     */
    @ApiOperation(value = "根据邮箱和id更新邮件为已读状态",notes = "根据邮箱和id更新邮件为已读状态")
    @PutMapping(value = "updateMessage")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "一个用户的messageId是唯一的，根据此获取邮箱信息",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String")
    })
    public GmailServiceResponse updateMessage(@RequestParam String emailAddress,@RequestParam String messageId){
         GmailServiceResponse response =new GmailServiceResponse();
         backendService.Update(messageId,emailAddress);
         response.setData("更新成功");
         return response;

    }


}

